<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>Document</title>
</head>

<body>
    <div id="info"></div>
    <script type="text/javascript" src="./lib/jquery.js"></script>
    <script type="text/javascript">
        function ajax(options) {
            var xhr = new XMLHttpRequest();
            var params = options.data;
            var pstr = "";
            for (var key in params) {
                var key = key;
                var value = params[key];
                pstr = key + "=" + value + "&";
            }
            //将data数据转化成字符串格式 ‘ABC=abc&’
            if (pstr.length > 0 && pstr.lastIndexOf("&") === pstr.length - 1) {
                pstr = pstr.substr(0, pstr.length - 1);
                //目的是截取从第一位到&的前一位
            }
            if (options.type === "get") {
                options.url += "?" + encodeURI(pstr);
                //在url之前加上？
            }
            xhr.open(options.type, options.url); //准备请求的参数
            if (options.type == "get") {
                xhr.send(null);
            } else if (options.type == "post") {
                xhr.setRequestHeader(
                    "content-type",
                    "application/x-www-form-urlencoded"
                );
                xhr.send(pstr);
            } //判断请求的类型 如果是post 那么请求发送的数据就是数据，且加上请求头 setRequestHeader
            //监听丰服务器的数据返回
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var res = xhr.responseText;
                    var object = JSON.parse(res);
                    options.success(object);
                }
            };
        }
        ajax({
            type: "get",
            data: {
                id: 1,
                bookname: "西游记",
            },
            url: "http://www.liulongbin.top:3006/api/getbooks",
            success: function(res) {
                consoel.log(res);
            },
        });
    </script>
</body>

</html>